#include <sys/time.h>
#include <time.h>
#include "../Tools/GLHeaders.hpp"
#include "IdleFunc.hpp"
#include "../Global.hpp"

void SleepGLScene(void){
  static bool first = true;
  static timeval previous_time;
  timeval current_time;
  double diff_time;
  struct timespec sleep_time;
  
  if(first){
    gettimeofday(&previous_time, NULL);
    first = false;
  }
  gettimeofday(&current_time, NULL);
  diff_time = current_time.tv_sec * 1000000 + current_time.tv_usec - (previous_time.tv_sec * 1000000 + previous_time.tv_usec);
  if(diff_time > (double)1/fps*1000000){
    gettimeofday(&previous_time, NULL);
    glutPostRedisplay();
  }
  else{
    sleep_time.tv_sec = (long)(current_time.tv_sec - previous_time.tv_sec);
    sleep_time.tv_nsec = (long)((double)1/fps*1000000000 - ((current_time.tv_usec - previous_time.tv_usec) * 1000));      
    nanosleep(&sleep_time, NULL);
  }
}
